<template>
  <el-card style="margin: 6px; padding-bottom: 10px">
    <el-tabs v-model="activeName" tab-position="left" style="padding: 10px; height: 780px" @tab-click="handleClick">
      <el-tab-pane name="play" style="padding-left: 10px">
        <span slot="label">
          <svg-icon icon-class="live1" style="font-size: 18px" />
          设备直播
        </span>
        <div style="">
          <player ref="player" :playerinfo="playinfo" class="components-container"></player>
          <div style="display: flex; margin-top: 30px">
            <el-row>
              <span style="font-size: 16px; margin: 10px">开启直播录像:</span>
              <el-switch v-model="playrecord" active-color="#13ce66" inactive-color="#c4c6c9" style="border-radius: 10px" @change="startPlayRecordk"></el-switch>
            </el-row>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane name="playback" style="padding-left: 10px">
        <span slot="label">
          <svg-icon icon-class="videotape" style="font-size: 20px" />
          设备录像
        </span>
        <div style="display: block; width: 940px">
          <player ref="playbacker" :playerinfo="playinfo" class="components-container"></player>
          <div style="display: flex; margin-top: 30px">
            <el-row>
              <span style="overflow: auto; font-size: 15px; margin-left: 10px">录像日期：</span>
              <el-date-picker v-model="queryDate" type="date" size="small" value-format="yyyy-MM-dd" clearable placeholder="选择日期" style="width: 200px" @change="loadDevRecord" />
              <span style="margin-left: 20px; overflow: auto; font-size: 15px">时间：</span>
              <el-button-group>
                <el-time-picker
                  size="small"
                  is-range
                  align="left"
                  v-model="timeRange"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  range-separator="至"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  @change="timePickerChange"
                  placeholder="选择时间范围"
                  style="width: 250px"
                ></el-time-picker>
              </el-button-group>

              <el-button-group style="margin: 0 20px">
                <el-button size="mini" type="primary" title="下载选定录像" @click="downloadRecord()">
                  <i class="el-icon-download" />
                  下载
                </el-button>
              </el-button-group>
            </el-row>
          </div>
        </div>
      </el-tab-pane>

      <!-- 用于设置间距 -->
      <el-tab-pane disabled>
        <span slot="label">
          <div style="margin-top: 560px"></div>
        </span>
      </el-tab-pane>

      <el-tab-pane name="device05" disabled>
        <span slot="label">
          <el-button type="info" size="mini" @click="goBack()">返回设备</el-button>
        </span>
      </el-tab-pane>
    </el-tabs>
  </el-card>
</template>

<script>
import player from '@/views/components/player/player.vue';
import { startPlay, playback, closeStream, playbackSeek } from '@/api/iot/channel';
import { getDevRecord, startDownloadRecord, startPlayRecord } from '@/api/iot/record';

export default {
  name: 'DevicePlayer',
  components: {
    player,
  },
  data() {
    return {
      activeName: 'play',
      deviceId: '',
      channelId: '',
      streamId: '',
      ssrc: '',
      playurl: '',
      queryDate: '',
      vodData: {},
      hisData: [],
      playinfo: {},
      playrecord: false,
      playrecording: false,
      playbackinfo: {},
      timeRange: null,
      startTime: null,
      endTime: null,
    };
  },
  beforeDestroy() {},
  activated() {
    // 跳转选项卡
    let activeName = this.$route.query.activeName;
    if (activeName != null && activeName !== '') {
      this.activeName = activeName;
    }
  },
  created() {
    if (this.$route.params) {
      this.deviceId = this.$route.params.deviceId;
      this.channelId = this.$route.params.channelId;
      let activeName = this.$route.params.activeName;
      if (activeName != null && activeName !== '') {
        this.activeName = activeName;
        if (this.activeName === 'play') {
          this.sendDevicePush();
        }
      }
      this.playinfo = {
        playtype: 'play',
        deviceId: this.deviceId,
        channelId: this.channelId,
      };
      this.playbackinfo = {
        playtype: 'playback',
        deviceId: this.deviceId,
        channelId: this.channelId,
      };
    }
  },
  destroyed() {
    this.closeStream();
    this.$refs.player.destroy();
    this.$refs.playbacker.destroy();
  },
  methods: {
    startPlayRecordk() {
      this.$refs.player.destroy();
      if (this.playrecord) {
        this.closeStream();
        startPlayRecord(this.deviceId, this.channelId).then((response) => {
          console.log('开始录像：' + this.deviceId + ' : ' + this.channelId);
          this.playrecording = true;
          const res = response.data;
          this.streamId = res.streamId;
          this.playurl = res.playurl;
          if (!this.$refs.player.isInit) {
            this.$refs.player.init();
          }
          this.$refs.player.play(res.playurl);
        });
      } else {
        this.playrecording = false;
        this.closeStream();
        this.sendDevicePush();
      }
    },
    handleClick(tab, event) {
      this.closeStream();
      if (tab.name === 'play') {
        this.$refs.playbacker.destroy();
        this.sendDevicePush();
      } else {
        this.$refs.player.destroy();
        this.$refs.playbacker.registercallback('playbackSeek', this.seekPlay);
      }
    },
    // 直播
    sendDevicePush: function () {
      console.log('通知设备推流1：' + this.deviceId + ' : ' + this.channelId);
      startPlay(this.deviceId, this.channelId).then((response) => {
        console.log('开始播放：' + this.deviceId + ' : ' + this.channelId);
        const res = response.data;
        this.streamId = res.streamId;
        this.playurl = res.playurl;
        if (!this.$refs.player.isInit) {
          this.$refs.player.init();
        }
        this.$refs.player.play(res.playurl);
      });
    },
    initUrl(data) {
      if (data) {
        this.streamId = data.ssrc;
        this.ssrc = data.ssrc;
        this.playurl = data.playurl;
      } else {
        this.streamId = '';
        this.ssrc = '';
        this.playurl = '';
      }
    },
    // 录像控制
    loadDevRecord() {
      if (this.deviceId && this.channelId) {
        const date = this.queryDate ? new Date(this.queryDate).getTime() : new Date(new Date().toLocaleDateString()).getTime();
        const start = date / 1000;
        const end = Math.floor((date + 24 * 60 * 60 * 1000 - 1) / 1000);
        const query = {
          start: start,
          end: end,
        };
        this.vodData = {
          start: start,
          end: end,
          base: start,
        };
        this.setTime(this.queryDate + ' 00:00:00', this.queryDate + ' 23:59:59');
        // this.hisData[0] = {
        //   start: start,
        //   end: end,
        // };
        // this.playback();
        getDevRecord(this.deviceId, this.channelId, query).then((res) => {
          this.hisData = res.data.recordItems;
          if (res.data.recordItems) {
            const len = this.hisData.length;
            if (len > 0) {
              if (this.hisData[0].start < start) {
                this.hisData[0].start = start;
                this.vodData.start = start;
              } else {
                this.vodData.start = this.hisData[0].start;
              }
              if (this.hisData[0].end < end) {
                this.vodData.end = this.hisData[0].end;
              }
              this.playback();
            } else {
              this.$message({
                type: 'warning',
                message: '请确认设备是否支持录像，或者设备SD卡是否正确插入！',
              });
            }
          } else {
            this.$message({
              type: 'warning',
              message: '请确认设备是否支持录像，或者设备SD卡是否正确插入！',
            });
          }
        });
      }
    },
    playback() {
      if (this.ssrc) {
        closeStream(this.deviceId, this.channelId, this.ssrc).then((res) => {
          const query = {
            start: this.vodData.start,
            end: this.vodData.end,
          };
          playback(this.deviceId, this.channelId, query)
            .then((res) => {
              this.playing = true;
              this.initUrl(res.data);
            })
            .finally(() => {
              this.triggerPlay(this.hisData);
            });
        });
      } else {
        const query = {
          start: this.vodData.start,
          end: this.vodData.end,
        };
        playback(this.deviceId, this.channelId, query)
          .then((res) => {
            this.playing = true;
            this.initUrl(res.data);
          })
          .finally(() => {
            this.triggerPlay(this.hisData);
          });
      }
    },
    triggerPlay(playTimes) {
      this.$refs.playbacker.playback(this.playurl, playTimes);
    },
    seekPlay(s) {
      const curTime = this.vodData.base + s.hour * 3600 + s.min * 60 + s.second;
      const seekRange = curTime - this.vodData.start;
      if (this.ssrc) {
        const query = {
          seek: seekRange,
        };
        const _this = this;
        playbackSeek(this.deviceId, this.channelId, this.streamId, query).then((res) => {
          _this.$refs.playbacker.setPlaybackStartTime(curTime);
        });
      }
    },
    closeStream() {
      if (this.activeName === 'play' && this.playrecording === true) {
        return;
      }
      if (this.streamId) {
        closeStream(this.deviceId, this.streamId).then((res) => {
          this.streamId = '';
          this.ssrc = '';
          this.playurl = '';
        });
      }
    },
    timePickerChange: function (val) {
      this.setTime(val[0], val[1]);
    },
    setTime: function (startTime, endTime) {
      this.startTime = startTime;
      this.endTime = endTime;
      this.timeRange = [startTime, endTime];
    },
    downloadRecord: function () {
      const start = new Date(this.startTime).getTime() / 1000;
      const end = new Date(this.endTime).getTime() / 1000;
      const query = {
        startTime: start,
        endTime: end,
        speed: '4',
      };
      startDownloadRecord(this.deviceId, this.channelId, query).then((res) => {
        console.log('开始下载录像：' + this.deviceId + ' : ' + this.channelId);
      });
    },
    /** 返回按钮 */
    goBack() {
      const obj = {
        path: '/iot/device',
        query: {
          t: Date.now(),
          pageNum: this.$route.query.pageNum,
        },
      };
      this.$tab.closeOpenPage(obj);
      this.reset();
    },
  },
};
</script>

<style scoped lang="scss">
::v-deep .el-switch__core {
  width: 50px !important;
  height: 26px !important;
  // border-radius: 3px;
  // background: #ffffff;
  // 开关小盒子
}
</style>
